<template>
  <div class="chat-container">
    <div class="chat-box">
      <div class="messages" ref="messageBox">
        <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.type]">
          {{ msg.content }}
        </div>
      </div>
      <div class="input-area">
        <el-input
          v-model="inputMessage"
          placeholder="请输入消息"
          @keyup.enter="sendMessage"
        >
          <template #append>
            <el-button @click="sendMessage">发送</el-button>
          </template>
        </el-input>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

const ws = ref(null)
const messages = ref([])
const inputMessage = ref('')
const messageBox = ref(null)

const connectWebSocket = () => {
  ws.value = new WebSocket('ws://localhost:8080/chat')
  
  ws.value.onopen = () => {
    messages.value.push({
      type: 'system',
      content: '已连接到服务器'
    })
  }
  
  ws.value.onmessage = (event) => {
    messages.value.push({
      type: 'received',
      content: event.data
    })
    scrollToBottom()
  }
  
  ws.value.onclose = () => {
    messages.value.push({
      type: 'system',
      content: '连接已断开'
    })
  }
  
  ws.value.onerror = (error) => {
    ElMessage.error('WebSocket连接错误')
    console.error('WebSocket错误:', error)
  }
}

const sendMessage = async () => {
  if (!inputMessage.value.trim()) {
    return
  }
  
  if (ws.value?.readyState === WebSocket.OPEN) {
    const messageData = {
      message: inputMessage.value
    }
    
    ws.value.send(JSON.stringify(messageData))
    messages.value.push({
      type: 'sent',
      content: inputMessage.value
    })
    
    inputMessage.value = ''
    await scrollToBottom()
  } else {
    ElMessage.error('未连接到服务器')
  }
}

const scrollToBottom = async () => {
  await nextTick()
  if (messageBox.value) {
    messageBox.value.scrollTop = messageBox.value.scrollHeight
  }
}

onMounted(() => {
  connectWebSocket()
})

onUnmounted(() => {
  if (ws.value) {
    ws.value.close()
  }
})
</script>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.chat-box {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  height: 600px;
  display: flex;
  flex-direction: column;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message {
  margin-bottom: 10px;
  padding: 8px 12px;
  border-radius: 4px;
  max-width: 70%;
}

.sent {
  background-color: #ecf5ff;
  margin-left: auto;
}

.received {
  background-color: #f4f4f5;
}

.system {
  background-color: #f2f6fc;
  color: #909399;
  text-align: center;
  margin: 10px auto;
}

.input-area {
  padding: 20px;
  border-top: 1px solid #dcdfe6;
}
</style> 